<template>
  <div>
    <div style="border: 1px solid #ccc;">
      <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" style="border-bottom: 1px solid #ccc" />
      <Editor
        :defaultConfig="editorConfig"
        :mode="mode"
        v-model="valueHtml"
        style="height: 400px; overflow-y: hidden"
        @onCreated="handleCreated"
        @onChange="handleChange"
        @onDestroyed="handleDestroyed"
        @onFocus="handleFocus"
        @onBlur="handleBlur"
        @customAlert="customAlert"
        @customPaste="customPaste"
      />
    </div>
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, onMounted, reactive, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { UPLOAD_URL, QINIU_URL } from '../config/config'
import { upload_qiniu } from '../config/api'
export default {
  components: { Editor, Toolbar },
  emits: ['change'],
  props: {
    value: String
  },
  setup(props, ctx) {
    console.log('-----------', props)
    // 编辑器实例，必须用 shallowRef，重要！
    const editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ref('<p></p>')

    const state = reactive({
      token: ''
    })

    watch(
      () => state.token,
      newVal => {
        console.log(newVal)
      }
    )

    // 模拟 ajax 异步获取内容
    onMounted(() => {
      gettoken()
      setTimeout(() => {
        valueHtml.value = '<p></p>'
        console.log(editorConfig)
      }, 1500)
    })

    const toolbarConfig = {
      toolbarKeys: [
        'bold', // 加粗
        'italic', // 斜体
        'through', // 删除线
        'underline', // 下划线
        'bulletedList', // 无序列表
        'numberedList', // 有序列表
        'color', // 文字颜色
        'insertLink', // 插入链接
        'fontSize', // 字体大小
        'lineHeight', // 行高
        'uploadImage', // 上传图片
        'delIndent', // 缩进
        'indent', // 增进
        'deleteImage', //删除图片
        'divider', // 分割线
        // 'insertImage', // 网络图片
        'insertTable', // 插入表格
        'justifyCenter', // 居中对齐
        'justifyJustify', // 两端对齐
        'justifyLeft', // 左对齐
        'justifyRight', // 右对齐
        'undo', // 撤销
        'redo', // 重做
        'clearStyle' // 清除格式
      ]
    }
    const editorConfig = { placeholder: '请输入内容...', scroll: true, MENU_CONF: {} }
    // editorConfig.MENU_CONF['uploadImage'].meta.token = state.token
    editorConfig.MENU_CONF['uploadImage'] = {
      server: UPLOAD_URL,
      // meta: {
      //   token: 'kZdC9RaAvAXGvjTx_gWx_DzvHjoZjI8lIAF1goWb:j-G1w78la_3muiE7HTN0SMZrx5A=:eyJzY29wZSI6InFndyIsImRlYWRsaW5lIjoxNjU0OTY3NzM2fQ=='
      // },
      fieldName: 'file',

      customUpload(file,insertFn) {
        // file 即选中的文件
        // 自己实现上传，并得到图片 url alt href
        // 最后插入图片
        const formData = new FormData()
            const xhr = new XMLHttpRequest();
            xhr.open('post', 'https://upload-z2.qiniup.com/', true)
            formData.append('file', file)
            formData.append('token', state.token)
            xhr.send(formData)
            xhr.onreadystatechange = ()=>{
             //请求成功时
             if(xhr.readyState == 4 && xhr.status == 200){

                 try {
                   let key = JSON.parse(xhr.response).key
                   insertFn(`${QINIU_URL}${key}`)
                   console.log('xxxxxxxxxxxxxxxxxxxxxxxx',key)
                 } catch (error) {
                   console.error('上传错误',error);
                 }

             }
         }
    },

      customInsert(res, insertFn) {
        // res 即服务端的返回结果
        // 从 res 中找到 url alt href ，然后插图图片
        insertFn(url, alt, href)
      },
      onProgress(progress) {
        // progress 是 0-100 的数字
        console.log('progress', progress)
      },
      // 单个文件上传成功之后
      onSuccess(file, res) {
        console.log(`${file.name} 上传成功`, res)
      },
      // 单个文件上传失败
      onFailed(file, res) {
        console.log(`${file.name} 上传失败`, res)
      },
      // 上传错误，或者触发 timeout 超时
      onError(file, err, res) {
        console.log(`${file.name} 上传出错`, err, res)
      }
    }
    // 组件销毁时，也及时销毁编辑器，重要！
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return

      editor.destroy()
    })

    // 编辑器回调函数
    const handleCreated = editor => {
      console.log('created', editor)
      editorRef.value = editor // 记录 editor 实例，重要！
    }
    const handleChange = editor => {
      console.log('change:', editor.getHtml())
      ctx.emit('change', editor.getHtml())
    }
    const handleDestroyed = editor => {
      console.log('destroyed', editor)
    }
    const handleFocus = editor => {
      console.log('focus', editor)
    }
    const handleBlur = editor => {
      console.log('blur', editor)
    }
    const customAlert = (info, type) => {
      alert(`【自定义提示】${type} - ${info}`)
    }
    const customPaste = (editor, event, callback) => {
      console.log('ClipboardEvent 粘贴事件对象', event)

      // 自定义插入内容
      editor.insertText('xxx')

      // 返回值（注意，vue 事件的返回值，不能用 return）
      callback(false) // 返回 false ，阻止默认粘贴行为
      // callback(true) // 返回 true ，继续默认的粘贴行为
    }
    //获取token
    const gettoken = async () => {
      const res = await upload_qiniu()
      state.token = res.data
      console.log(1111)
    }
    return {
      editorRef,
      mode: 'default',
      valueHtml,
      toolbarConfig,
      editorConfig,
      handleCreated,
      handleChange,
      handleDestroyed,
      handleFocus,
      handleBlur,
      customAlert,
      customPaste,
      state,
      gettoken
    }
  }
}
</script>
